"""
@function
Report everyday practices via email.

@cron
10 9 * * *

@command
python3 main.py

@detail
Get the questions from the question bank and get the answers via baidu wenxin 3.5,
and finally organize it into an HTML file and send it to the recipients by email.

Reference: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu
"""
import json
from helper.questions_fetcher import Question_Fetcher
from helper.answers_fetcher import Answers_Fetcher
from helper.html_generator import HTML_Generator
from helper.email_sender import Email_Sender
from helper.common import data_dir, logger

def load_config(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        config_data = json.load(f)
    return config_data

def read_access_token(file_path):
    with open(file_path, "r", encoding="utf-8") as file:
        access_token = file.read().strip()
    return access_token

def main():
    logger.warning("Script begin......................")
    qf = Question_Fetcher('questions.json')
    questions = qf.get_random_questions(1)
    
    access_token = read_access_token('access_token')
    af = Answers_Fetcher(access_token, data_dir)
    res = af.fetch_and_save_answers(questions)
    if res is None:
        logger.error("Fetch answers failed")
        return
    
    hg = HTML_Generator(data_dir)
    html_file = hg.generate()
    if res is None:
        return

    config = load_config('config.json')
    smtp_settings = config.get('smtp_settings', {})
    smtp_server = smtp_settings.get('server')
    smtp_port = smtp_settings.get('port')
    smtp_user = smtp_settings.get('user')
    smtp_password = smtp_settings.get('password')
    es = Email_Sender(smtp_server, smtp_port, smtp_user, smtp_password)
    
    body = es.read_file(html_file)
    recipients = ['alonely2021@qq.com',
                  'yubin0166@163.com',
                  '3055696441@qq.com',
                  'xidexide49@gmail.com',
                  'sbsrjggmxd@163.com',
                  'pjb0216@163.com',
                  'sny_sprit@163.com',
                  'tian18225309164@163.com',
                  '879862426@qq.com',
                  'memorial77@163.com',
                  '3311922913@qq.com']

    es.send_email("☕️每日一八股💪", body, recipients)

    logger.warning("Script end success......................")

if __name__ == '__main__':
    main()
